/*
 * =====================================================================================
 *
 *       Filename:  convexity.cpp
 *
 *    Description:  Returns convexity of given character
 *
 *        Version:  1.0
 *        Created:  04/07/12 16:34:48
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Moos Hueting (mh), mooshueting@gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdlib.h>
#include <iostream>
#include <cv.h>
#include <highgui.h>

using namespace std;
using namespace cv;

float convexity(Mat src) {
    Size s = src.size();

    int minx = 1000;
    int maxx = 0;
    int miny = 1000;
    int maxy = 0;

    for (int i = 0; i < s.height; i++) {
        for (int j = 0; j < s.width; j++) {
            // if the current pixel is set
            if (src.at<unsigned char>(i, j) > 0) { 
                if (i < miny)
                    miny = i;
                if (i > maxy)
                    maxy = i;
                if (j < minx)
                    minx = j;
                if (j > maxx)
                    maxx = j;
            }
        }
    }

    int boundingArea = ((maxx + 1) - minx) * ((maxy + 1) - miny);

    return (float)boundingArea / countNonZero(src);
}

int main(int argc, char* argv[]) {

    if (argc == 1) {
        std::cerr << "Please specify image file." << std::endl;
        return -1;
    }

    Mat im = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
    threshold(im, im, 100, 255, THRESH_BINARY);

    std::cout << convexity(im) << std::endl;
}
